const path = require('path');

module.exports = async ctx => {
    console.log('上传文件');
    const { files } = ctx.request;
    if (!files || !files.file) {
        ctx.throw(400, 'No file uploaded');
    } else {
        // 把文件存储到 files 目录下
        const file = files.file;
        const fs = require('fs');
        const path = require('path');
        const uploadDir = path.join(__dirname, '../../../../../../files');
        // const filePath = path.join(uploadDir, file.name);
        // // 确保上传目录存在
        if (!fs.existsSync(uploadDir)) {
            fs.mkdirSync(uploadDir, { recursive: true });
        }
        // 移动文件到指定目录，改名称未dsff，如果存在他替换
        const newFilePath = path.join(uploadDir, 'dsff');
        fs.renameSync(file.filepath, newFilePath); // 移动文件并重命名
        // 返回文件路径
        ctx.body = {
            success: true,
            message: 'File uploaded successfully',
            filePath: '/files/dsff' // 返回相对路径
        };
        console.log(`File uploaded to: ${newFilePath}`);
    }

    ctx.status = 200;
}